package com.mercycrazy.recruit.retry;

import com.mercycrazy.recruit.util.tencent.SMSUtils;
import com.mercycrazy.recruit.vo.mq.SendSMS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

/**
 * 短信发送重试能力
 *
 * @author <a href="mailto:1443424326@qq.com">mercycrazy</a>
 * @since 2023-01-19
 */
@Slf4j
@EnableRetry
@Service
public class RetrySMSService {

    private final SMSUtils smsUtils;

    public RetrySMSService(SMSUtils smsUtils) {
        this.smsUtils = smsUtils;
    }

    /**
     * 发送短信, 异常重试
     */
    @Retryable(
            maxAttempts = 5,
            backoff = @Backoff(
                    delay = 100L,
                    multiplier = 2
            ))
    public Boolean sendSMSWithRetry(SendSMS sendSMS) throws Exception {
        return smsUtils.sendSMS(sendSMS.getPhone(), sendSMS.getContent(), sendSMS.getValidTime());
    }

    @Recover
    public Boolean recover() {
        log.error("短信发送失败!");
        return Boolean.FALSE;
    }
}
